#include "shmipc/core/shm_mutex.h"

#include <errno.h>
#include <string.h>
#include <stdio.h>

namespace shmipc::core {
ShmMutex::ShmMutex() {
    pthread_mutexattr_t  attr;
    pthread_mutexattr_init(&attr);
    pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
    pthread_mutexattr_setrobust(&attr, PTHREAD_MUTEX_ROBUST);
    pthread_mutex_init(&mutex_, &attr);

    pthread_mutexattr_destroy(&attr);
}

ShmMutex::~ShmMutex() {
    pthread_mutex_destroy(&mutex_);
}

int ShmMutex::lock() {
    int ret = pthread_mutex_lock(&mutex_);
    if (ret == EOWNERDEAD){
        printf("Shm Mutex Oner Dead Err: %s\n", strerror(errno));
        return pthread_mutex_consistent(&mutex_);
    }
    return ret;
}

int ShmMutex::unlock() {
    return pthread_mutex_unlock(&mutex_);
}

} //namespace shmipc::core